<template>
  <el-container class="layout-container">
    <!-- 侧边栏 -->
    <el-aside width="200px">
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        :router="true"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
      >
        <el-menu-item index="/home">
          <el-icon><DataLine /></el-icon>
          <span>数据概览</span>
        </el-menu-item>
        <el-menu-item index="/home/skills">
          <el-icon><Connection /></el-icon>
          <span>技能分析</span>
        </el-menu-item>
        <el-menu-item index="/home/salary">
          <el-icon><Money /></el-icon>
          <span>薪资分析</span>
        </el-menu-item>
        <el-menu-item index="/home/education">
          <el-icon><Reading /></el-icon>
          <span>学历分析</span>
        </el-menu-item>
        <el-menu-item index="/home/city-compare">
          <el-icon><Location /></el-icon>
          <span>城市对比</span>
        </el-menu-item>
        <el-menu-item index="/home/profile-match">
          <el-icon><UserFilled /></el-icon>
          <span>个人画像匹配</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主要内容区 -->
    <el-container>
      <!-- 头部 -->
      <el-header>
        <div class="header-left">
          <h2>招聘市场需求智能感知系统</h2>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-dropdown">
              <el-avatar :size="32" :src="userAvatar" />
              <span class="username">{{ username }}</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 内容区 -->
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>

    <!-- 个人信息对话框 -->
    <el-dialog
      v-model="profileDialogVisible"
      title="个人信息"
      width="500px"
    >
      <div v-if="!isEditing" class="profile-info">
        <div class="avatar-container">
          <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar" />
        </div>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ userInfo.realName }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ userInfo.age }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ userInfo.gender }}</el-descriptions-item>
          <el-descriptions-item label="学历">{{ userInfo.education }}</el-descriptions-item>
          <el-descriptions-item label="专业">{{ userInfo.major }}</el-descriptions-item>
          <el-descriptions-item label="工作经验">{{ userInfo.experience }}年</el-descriptions-item>
          <el-descriptions-item label="技能">
            <el-tag v-for="skill in userInfo.skills" :key="skill" class="skill-tag">
              {{ skill }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="期望城市">{{ userInfo.preferredCity }}</el-descriptions-item>
          <el-descriptions-item label="期望职位">{{ userInfo.preferredPosition }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else>
        <el-form
          ref="formRef"
          :model="editForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="头像URL" prop="avatar">
            <el-input v-model="editForm.avatar" placeholder="请输入头像URL">
              <template #append>
                <el-button @click="previewAvatar">预览</el-button>
              </template>
            </el-input>
            <div v-if="editForm.avatar" class="avatar-preview">
              <el-avatar :size="100" :src="editForm.avatar" />
            </div>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" />
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input-number v-model="editForm.age" :min="18" :max="100" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="editForm.gender">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="学历" prop="education">
            <el-select v-model="editForm.education">
              <el-option label="大专" value="大专" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
          </el-form-item>
          <el-form-item label="专业" prop="major">
            <el-input v-model="editForm.major" />
          </el-form-item>
          <el-form-item label="工作经验" prop="experience">
            <el-input-number v-model="editForm.experience" :min="0" :max="50" />
          </el-form-item>
          <el-form-item label="技能" prop="skills">
            <el-select
              v-model="editForm.skills"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入技能"
            >
              <el-option
                v-for="skill in skillOptions"
                :key="skill"
                :label="skill"
                :value="skill"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="期望城市" prop="preferredCity">
            <el-select v-model="editForm.preferredCity">
              <el-option label="北京" value="北京" />
              <el-option label="上海" value="上海" />
              <el-option label="广州" value="广州" />
            </el-select>
          </el-form-item>
          <el-form-item label="期望职位" prop="preferredPosition">
            <el-input v-model="editForm.preferredPosition" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="profileDialogVisible = false">取消</el-button>
          <el-button v-if="!isEditing" type="primary" @click="startEditing">
            修改信息
          </el-button>
          <el-button v-else type="primary" @click="handleUpdate">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { DataLine, Connection, Money, Reading, Location, UserFilled } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const route = useRoute()

// 用户信息
const username = ref('')
const userAvatar = ref('')
const defaultAvatar = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRQxgz7HPPrS68XByNwCeg5UuL2xnh_Jyrh5Q&s'

// 个人信息对话框
const profileDialogVisible = ref(false)
const isEditing = ref(false)
const userInfo = ref({})
const editForm = ref({})
const formRef = ref(null)

// 技能选项
const skillOptions = [
  'Java', 'Python', 'JavaScript', 'C++', 'C#', 'Go',
  'React', 'Vue', 'Angular', 'Node.js', 'Spring Boot',
  'MySQL', 'PostgreSQL', 'MongoDB', 'Redis',
  'Docker', 'Kubernetes', 'AWS', 'Azure', 'GCP',
  'Linux', 'Git', 'CI/CD', 'DevOps'
]

// 表单验证规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  education: [
    { required: true, message: '请选择学历', trigger: 'change' }
  ],
  major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
  experience: [
    { required: true, message: '请输入工作经验', trigger: 'blur' }
  ],
  skills: [
    { required: true, message: '请选择技能', trigger: 'change' }
  ],
  preferredCity: [
    { required: true, message: '请选择期望城市', trigger: 'change' }
  ],
  preferredPosition: [
    { required: true, message: '请输入期望职位', trigger: 'blur' }
  ],
  avatar: [
    { pattern: /^(http|https):\/\/.+/, message: '请输入有效的URL地址', trigger: 'blur' }
  ]
}

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('未找到用户ID')
      return
    }

    const response = await axios.get(`http://localhost:8081/api/user/info/${userId}`)
    if (response.data.code === 200) {
      userInfo.value = response.data.data
      username.value = userInfo.value.username
      userAvatar.value = userInfo.value.avatar || defaultAvatar
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'profile') {
    profileDialogVisible.value = true
    fetchUserInfo()
  } else if (command === 'logout') {
    localStorage.removeItem('userId')
    router.push('/login')
  }
}

// 开始编辑
const startEditing = () => {
  isEditing.value = true
  editForm.value = { ...userInfo.value }
}

// 预览头像
const previewAvatar = () => {
  if (editForm.value.avatar) {
    userAvatar.value = editForm.value.avatar
  }
}

// 更新用户信息
const handleUpdate = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.put('http://localhost:8081/api/user/update', editForm.value)
        if (response.data.code === 200) {
          ElMessage.success('更新成功')
          userInfo.value = { ...editForm.value }
          userAvatar.value = editForm.value.avatar || defaultAvatar
          isEditing.value = false
          profileDialogVisible.value = false
        }
      } catch (error) {
        if (error.response?.data?.code === 500) {
          ElMessage.error('邮箱已存在，请修改邮箱')
        } else {
          ElMessage.error('更新失败')
        }
      }
    }
  })
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.el-aside {
  background: linear-gradient(180deg, #2c3e50 0%, #1a252f 100%);
  color: #fff;
  box-shadow: 4px 0 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.el-menu) {
  border-right: none;
  background: transparent;
}

:deep(.el-menu-item) {
  height: 56px;
  line-height: 56px;
  margin: 4px 0;
  border-radius: 0 28px 28px 0;
  margin-right: 16px;
  transition: all 0.3s ease;
}

:deep(.el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.1);
}

:deep(.el-menu-item.is-active) {
  background: #409EFF;
  color: #fff;
}

:deep(.el-menu-item .el-icon) {
  margin-right: 12px;
  font-size: 18px;
}

.el-header {
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 64px;
}

.header-left h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.user-dropdown:hover {
  background: rgba(0, 0, 0, 0.04);
}

.username {
  margin-left: 8px;
  font-size: 14px;
  color: #2c3e50;
}

.el-main {
  padding: 24px;
  background-color: #f5f7fa;
}

:deep(.el-card) {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  font-weight: 600;
}

.profile-info {
  padding: 20px;
}

.avatar-container {
  text-align: center;
  margin-bottom: 24px;
}

.skill-tag {
  margin: 4px;
  border-radius: 4px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #2c3e50;
}

:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

:deep(.el-dialog__title) {
  color: #fff;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #fff;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
}
</style> 